package org.execute.tool.adsPower;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BasicOperations {

    /**
     * 从已有的 WebDriver 中提取所有插件的信息
     */
    public static List<Map<String, String>> getAllPlugins(AdsPowerWebAction webAction) {
        List<Map<String, String>> allPlugins = new ArrayList<>();

        try {
            // 1. 导航到浏览器扩展程序页面
            webAction.navigateTo("chrome://extensions/");

            // 2. 开启开发者模式（插件ID仅在开发者模式下显示）
            WebElement devModeToggle = webAction.waitForElementVisible(
                            By.cssSelector("div[class*='more-actions']"));

            // 若未开启，则点击开启
            WebElement devModeCheckbox = webAction.findElement(By.id("devMode"));
            if (!devModeCheckbox.isSelected()) {
                devModeToggle.click();
                // 等待开发者模式生效（使用默认超时）
                webAction.waitForCondition(
                        ExpectedConditions.elementSelectionStateToBe(
                                By.id("devMode"), true
                        )
                );
            }

            // 3. 等待插件列表加载完成
            webAction.waitForCondition(
                    ExpectedConditions.presenceOfElementLocated(
                            By.cssSelector("div[class*='extension-card'], extensions-item")
                    )
            );

            // 4. 获取所有插件卡片并解析信息（兼容不同DOM结构）
            List<WebElement> pluginCards = new ArrayList<>();
            try {
                // 尝试第一种选择器
                pluginCards = webAction.findElements(By.cssSelector("div[class*='extension-card']"));
                if (pluginCards.isEmpty()) {
                    // 尝试第二种选择器（针对新版Chrome）
                    pluginCards = webAction.findElements(By.cssSelector("extensions-item"));
                }
            } catch (Exception e) {
                System.err.println("获取插件卡片时出错：" + e.getMessage());
            }

            for (WebElement card : pluginCards) {
                try {
                    Map<String, String> pluginInfo = new HashMap<>();

                    // 提取插件名称（兼容不同结构）
                    String pluginName = extractPluginName(webAction, card);
                    if (pluginName == null) continue;
                    pluginInfo.put("pluginName", pluginName);

                    // 提取插件ID
                    String pluginId = extractPluginId(webAction, card);
                    if (pluginId == null) continue;
                    pluginInfo.put("pluginId", pluginId);

                    // 提取插件状态
                    String status = extractPluginStatus(webAction, card);
                    pluginInfo.put("status", status);

                    // 提取插件版本
                    String version = extractPluginVersion(webAction, card);
                    pluginInfo.put("version", version);

                    allPlugins.add(pluginInfo);

                } catch (Exception e) {
                    System.err.println("解析插件信息失败：" + e.getMessage());
                    continue;
                }
            }

        } catch (Exception e) {
            System.err.println("获取插件列表失败：" + e.getMessage());
        }

        return allPlugins;
    }

    /**
     * 根据名称查找插件
     */
    public static Map<String, String> getNamePlugins(AdsPowerWebAction webAction, String name) {
        if (name == null || name.trim().isEmpty()) {
            System.out.println("插件名称不能为空");
            return null;
        }

        List<Map<String, String>> allPlugins = getAllPlugins(webAction);

        for (Map<String, String> plugin : allPlugins) {
            String pluginName = plugin.get("pluginName");
            if (pluginName != null && pluginName.equalsIgnoreCase(name.trim())) {
                System.out.println("找到插件，名称：" + pluginName + "，ID：" + plugin.get("pluginId"));
                return plugin;
            }
        }

        System.out.println("未找到名称为[" + name + "]的插件");
        return null;
    }

    /**
     * 打开指定名称的插件
     */
    public static boolean openPlugin(AdsPowerWebAction webAction, String name) {
        // 1. 查找插件
        Map<String, String> targetPlugin = getNamePlugins(webAction, name);
        if (targetPlugin == null) {
            return false;
        }

        // 2. 获取插件ID
        String pluginId = targetPlugin.get("pluginId");
        if (pluginId == null || pluginId.trim().isEmpty()) {
            System.out.println("插件ID无效或为空");
            return false;
        }

        // 3. 尝试打开插件的不同可能页面
        List<String> possiblePaths = Arrays.asList(
                "popup.html",
                "index.html",
                "options.html",
                "main.html",
                ""  // 尝试根路径
        );

        for (String path : possiblePaths) {
            String pluginUrl = "chrome-extension://" + pluginId + (path.isEmpty() ? "" : "/" + path);
            try {
                webAction.navigateTo(pluginUrl);

                // 验证页面是否加载成功
                webAction.waitForCondition(
                        ExpectedConditions.presenceOfElementLocated(By.tagName("body"))
                );

                System.out.println("已成功打开插件页面：" + pluginUrl);
                return true;
            } catch (Exception e) {
                System.out.println("尝试打开路径[" + path + "]失败：" + e.getMessage());
            }
        }

        System.out.println("所有可能的插件页面路径都无法打开");
        return false;
    }

    // 以下为辅助方法，保持不变
    private static String extractPluginName(AdsPowerWebAction webAction, WebElement card) {
        try {
            return card.findElement(By.cssSelector("div[class*='extension-name'], .name")).getText().trim();
        } catch (Exception e1) {
            try {
                return card.findElement(By.xpath(".//*[contains(@class, 'name')]")).getText().trim();
            } catch (Exception e2) {
                System.err.println("无法提取插件名称：" + e2.getMessage());
                return null;
            }
        }
    }

    private static String extractPluginId(AdsPowerWebAction webAction, WebElement card) {
        try {
            return card.findElement(
                    By.xpath(".//*[contains(text(), 'ID:')]/following-sibling::*")
            ).getText().trim();
        } catch (Exception e1) {
            try {
                String id = card.getAttribute("id");
                if (id != null && !id.isEmpty()) {
                    return id;
                }
                throw new Exception("ID属性为空");
            } catch (Exception e2) {
                System.err.println("无法提取插件ID：" + e2.getMessage());
                return null;
            }
        }
    }

    private static String extractPluginStatus(AdsPowerWebAction webAction, WebElement card) {
        try {
            return card.findElement(
                    By.cssSelector("button[class*='toggle-button'], .enable-disable-button")
            ).getText().trim();
        } catch (Exception e) {
            try {
                if (card.getAttribute("class").contains("enabled")) {
                    return "已启用";
                } else {
                    return "已禁用";
                }
            } catch (Exception e2) {
                System.err.println("无法提取插件状态，使用默认值：未知");
                return "未知";
            }
        }
    }

    private static String extractPluginVersion(AdsPowerWebAction webAction, WebElement card) {
        try {
            WebElement versionElement = card.findElement(
                    By.cssSelector("div[class*='extension-version'], .version")
            );
            String version = versionElement.getText().trim();
            return version.replaceAll("版本\\s*", "");
        } catch (Exception e) {
            return "未知版本";
        }
    }
}
